package 几数之和.三数之和和四数之和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 四数之和 ，三数之和的遍历
 * @date 2022/10/17 11:02
 */
public class Demo18 {
    public static void main(String[] args) {
        //[-3,-2,-1,0,0,1,2,3]
        //0
        int[] nums=new int[]{1000000000,1000000000,1000000000,1000000000};
        List<List<Integer>> lists = fourSum(nums,-294967296);
        System.out.println(lists);
    }
    public  static  List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res=new ArrayList<>();
        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {
            //先裁剪
            if(nums[i]>target&&nums[i]>0&&target>0){
                return  res;
            }
            if(i>0&&nums[i]==nums[i-1]){
                //去重
                continue;
            }
            for (int j = i+1; j < nums.length; j++){
                //裁剪
                if((nums[i]+nums[j])>target&&nums[j]>0&&target>0){
                    return  res;
                }
                if(j>i+1&&nums[j]==nums[j-1]){
                    //去重
                    continue;
                }
                int left=j+1;
                int right=nums.length-1;
                while (left<right){
                    long sum = (long) nums[i] + (long) nums[j] + (long) nums[left] + (long)nums[right];
                    //三数之和为0.这里改成target
                    if(sum>target){
                        right--;
                    }else if(sum<target){
                        left++;
                    }else {
                        res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        while (left<right&&nums[left]==nums[left+1]){
                            left++;
                        }
                        while (left<right&&nums[right]==nums[right-1]){
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
        }
        return res;
    }
}
